package com.limeng.dao.impl;

import java.util.ArrayList;
import java.util.List;

import com.limeng.domain.DAOAddress;
import com.limeng.exceptions.DAOException;
import com.limeng.hibernate.ModelUtil;
import com.limeng.model.Address;
import com.limeng.model.bean.AddressB;

public class DAOAddressImpl extends DAOAddress {

	@Override
	public Address loadAddress(Long id) throws DAOException {
		Address address = null;
		try {
			ModelUtil.getSession().beginTransaction();
			address = (Address) ModelUtil.getSession().get(Address.class, id);
			ModelUtil.getSession().getTransaction().commit();
		} catch (Exception e) {
			if (id != null) {
				throw new DAOException("Could not retrieve objects with id  "
						+ id + ".  " + e.getMessage());
			} else {
				throw new DAOException(
						"Could not retrieve objects with null id.  "
								+ e.getMessage());
			}
		}
		if (address == null) {
			if (id != null) {
				throw new DAOException("Could not find object with id  " + id
						+ ".  ");
			} else {
				throw new DAOException("Could not find object with null id ");
			}
		}
		return address;
	}

	@Override
	public Address saveAddress(Address address) throws DAOException {
		try {
			ModelUtil.getSession().beginTransaction();
			if (address.getAddressID() != null) {
				ModelUtil.getSession().load(Address.class,
						address.getAddressID());
				ModelUtil.getSession().update(address);
			} else {
				ModelUtil.getSession().save(address);
			}
			ModelUtil.getSession().getTransaction().commit();
			return address;
		} catch (Exception e) {
			if (address == null) {
				throw new DAOException(
						"Could not retrieve objects for null criteria " + ".  "
								+ e.getMessage());
			} else {
				throw new DAOException(
						"Could not retrieve objects for criteria : "
								+ address.toString() + ".  " + e.getMessage());
			}
		}
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Address> getAllAddress() throws DAOException {
		ModelUtil.getSession().beginTransaction();
		List<Address> addressList = ModelUtil.getSession()
				.createCriteria(Address.class).list();
		ModelUtil.getSession().getTransaction().commit();
		return addressList;
	}

	@Override
	public List<AddressB> getAllAddressB() throws DAOException {
		ModelUtil.getSession().beginTransaction();
		List<AddressB> addressBList=new ArrayList<AddressB>();
		List<Address> addressList = ModelUtil.getSession()
				.createCriteria(Address.class).list();
		ModelUtil.getSession().getTransaction().commit();
		for(Address address:addressList)
		{
			addressBList.add(address.getBean());
		}
		return addressBList;
	}

}
